import { Injectable, NotFoundException } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { User } from 'src/auth/user.entity';
import { DataSource, Repository } from 'typeorm';
import { CreateTaskDto } from './dto/create-task.dto';
import { GetTasksFilterDto } from './dto/get-tasks-filter.dot';
import { UpdateTaskStatusDto } from './dto/update-task-status.dto';
import { TaskStatus } from './task.status.enum';
import { Task } from './tast.entity';

@Injectable()
export class TasksService {
  constructor(
    @InjectRepository(Task)
    private readonly tasksRepository: Repository<Task>,
    private dataSource: DataSource,
  ) {}

  async getTasks(filterDto: GetTasksFilterDto, user: User): Promise<Task[]> {
    console.log('能拿到 dataSource', this.dataSource.name);
    const { status, search } = filterDto;
    const query = await this.tasksRepository.createQueryBuilder('task');
    query.where({ user });

    if (status) {
      query.andWhere('task.status = :status', { status });
    }

    if (search) {
      query.andWhere(
        'LOWER(task.title) LIKE LOWER(:search) OR LOWER(task.description) LIKE LOWER(:search)',
        { search: `%${search}%` },
      );
    }

    const tasks = await query.getMany();

    return tasks;
  }

  async getTaskById(id: string, user: User): Promise<Task> {
    const task = this.tasksRepository.findOne({
      where: {
        id,
        user,
      },
    });

    if (!task) {
      throw new NotFoundException(`Task with id ${id} not found`);
    }

    return task;
  }

  async createTask(createTaskDto: CreateTaskDto, user: User): Promise<Task> {
    const task = await this.createTaskRepository(createTaskDto, user);

    return task;
  }

  async createTaskRepository(
    createTaskDto: CreateTaskDto,
    user: User,
  ): Promise<Task> {
    const { title, description } = createTaskDto;
    const task = this.tasksRepository.create({
      title,
      description,
      status: TaskStatus.OPEN,
      user,
    });

    await this.tasksRepository.save(task);
    return task;
  }

  async delTaskById(id: string, user: User): Promise<boolean> {
    const res = await this.tasksRepository.delete({ id, user });
    if (res.affected === 0) {
      throw new NotFoundException(`Task with id ${id} not found`);
    }
    return !!res?.affected;
  }

  async updateTaskStatusById(
    id: string,
    updateTaskStatusDto: UpdateTaskStatusDto,
    user: User,
  ): Promise<Task> {
    const task = await this.getTaskById(id, user);
    console.log(task, 1);
    task.status = updateTaskStatusDto.status;
    console.log(updateTaskStatusDto);
    const res = await this.tasksRepository.save(task);
    console.log(res);
    return task;
  }

  // async updateTaskById(
  //   id: string,
  //   updateTaskStatusDto: UpdateTaskStatusDto,
  // ): Promise<Task> {
  //   const task = await this.tasksRepository.preload(updateTaskStatusDto);
  // }

  // createTask(createTaskDto: CreateTaskDto) {
  //   const { title, description } = createTaskDto;
  //   // const task =
  //   // const task: Task = {
  //   //   id: Date.now().toString(),
  //   //   title,
  //   //   description,
  //   //   status: TaskStatus.OPEN,
  //   // };
  //   // this.tasks.push(task);
  //   return task;
  // }

  // private tasks: Task[] = [];

  // getAllTasks(): Task[] {
  //   return this.tasks;
  // }
  // getFilterTasks(filterDto: GetTasksFilterDto): Task[] {
  //   const { status, search } = filterDto;
  //   let tasks = this.getAllTasks();
  //   if (status) {
  //     tasks = tasks.filter((e) => e.status === status);
  //   }
  //   if (search) {
  //     tasks = tasks.filter((e) => {
  //       if (e.title.includes(search) || e.description.includes(search)) {
  //         return true;
  //       }
  //       return false;
  //     });
  //   }
  //   return tasks;
  // }
  // findById(id: string): Task {
  //   const task = this.tasks.find((e) => e.id == id);
  //   if (!task) {
  //     throw new NotFoundException();
  //   }
  //   return task;
  // }
  // delById(id: string): Task {
  //   const task = this.findById(id);
  //   this.tasks.filter((e) => e.id == task.id);
  //   return task;
  // }
  // updateStatusById(id: string, updateTaskStatusDto: UpdateTaskStatusDto) {
  //   const { status } = updateTaskStatusDto;
  //   const task = this.findById(id);
  //   console.log(updateTaskStatusDto);
  //   task.status = status;
  //   return task;
  // }
  // createTask(createTaskDto: CreateTaskDto) {
  //   const { title, description } = createTaskDto;
  //   const task: Task = {
  //     id: Date.now().toString(),
  //     title,
  //     description,
  //     status: TaskStatus.OPEN,
  //   };
  //   this.tasks.push(task);
  //   return task;
  // }
}
